﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ProductManage_WCG.Models;

namespace ProductManage_WCG.Controllers
{
    public class HomeController : Controller
    {
        Model1 model = new Model1();
        public ActionResult Index(int Type=0,string Name="")
        {
            var proType = model.ProType.ToList();
            //插入首选项
            proType.Insert(0, new ProType() { ID = 0, Name = "全部" });
            //填充下拉框
            ViewBag.Type = new SelectList(proType, "ID", "Name");
            //多条件查询
            var list = model.ProInfo.Where(p => p.Name.Contains(Name) && (Type == 0 || p.Type == Type)).ToList();
            if (list.Count==0)
            {
                ViewBag.Tips = "T";
            }
            return View(list);
        }

        public ActionResult Create()
        {

            ViewBag.Type = new SelectList(model.ProType, "ID", "Name");
            return View();
        }
        [HttpPost]
        public ActionResult Create(ProInfo proInfo)
        {
            if (ModelState.IsValid)
            {
                proInfo.IsDestroy = false;
                string time=proInfo.AddTime.ToString().Remove(8,8);
                string time2 = DateTime.Now.ToString().Remove(0, 9);
                proInfo.AddTime = DateTime.Parse(time + time2);
                //执行添加
                model.ProInfo.Add(proInfo);
                //保存至数据库
                
                if (model.SaveChanges()>0)
                {
                    //如果添加成功返回主页
                    return RedirectToAction("Index");
                }
            }
            // 如果没添加成功
            ViewBag.Type = new SelectList(model.ProType, "ID", "Name");
            return View(proInfo);
        }
        [HttpPost]
        public ActionResult Edit(int? id)
        {
            if (id==null)
            {
                return Json(false);
            }
            var list = model.ProInfo.FirstOrDefault(p=>p.ID==id);
            if (list==null)
            {
                return Json(false);
            }
            //执行报废
            list.IsDestroy = true;
            var res = model.SaveChanges() > 0;
            //保存至数据库
            if (res)
            {
                return Json(res);
            }
            return View(false);
        }
    }
}